package com.example.myword;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.room.Room;

import com.example.myword.dao.Word;
import com.example.myword.dao.WordDao;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownLoadService extends IntentService {

    private static final String TAG = "WordService";
    public static final String ACTION_DOWNLOAD_COMPLETE = "com.example.myword.ACTION_DOWNLOAD_COMPLETE";
    public static final String ACTION_DOWNLOAD_FAILED = "com.example.myword.ACTION_DOWNLOAD_FAILED";
    private WordDao wordDao;// 初始化 WordDao
    private AppDatabase db;

    public DownLoadService() {
        super("DownLoadService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "word-database").allowMainThreadQueries().build();
        wordDao = db.wordDao();

        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://10.155.237.253:5000/words")
                    .build();

            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            Log.i(TAG, responseData);

            // 解析 JSON 数据
            JSONArray jsonArray = new JSONArray(responseData);
            ArrayList<Word> words = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String word = jsonObject.getString("word");
                String definition = jsonObject.getString("definition");
                words.add(new Word("current_user_id", word, definition, false));
            }
            // 将数据存储到本地数据库
            for (Word word : words) {
                wordDao.insert(word);
            }

            // 发送成功广播
            Intent successIntent = new Intent(ACTION_DOWNLOAD_COMPLETE);
            LocalBroadcastManager.getInstance(this).sendBroadcast(successIntent);

        } catch (IOException | JSONException e) {
            e.printStackTrace();
            // 发送失败广播
            Intent failedIntent = new Intent(ACTION_DOWNLOAD_FAILED);
            LocalBroadcastManager.getInstance(this).sendBroadcast(failedIntent);
        }
    }
}
